package com.itheima.miankuangjia;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;

public class BeanFactory1 {
    private BeanFactory1(){}
    private static HashMap<Object,Object> hm=new HashMap<>();
    static{
        try {
            ClassLoader classLoader = BeanFactory1.class.getClassLoader();
            String path = classLoader.getResource("element.xml").getPath();
            Document parse = Jsoup.parse(new File(path), "UTF-8");
            Elements elements = parse.getElementsByTag("bean");
            for (Element element : elements) {
                String idvalue = element.attr("id");
                String classvalue = element.attr("class");
                Class<?> clazz = Class.forName(classvalue);
                Constructor<?> con = clazz.getDeclaredConstructor();
                con.setAccessible(true);
                Object obj = con.newInstance();
                Elements pro = element.getElementsByTag("property");
                for (Element element1 : pro) {
                    String namevale = element1.attr("name");
                    String value = element1.attr("value");
                    //
                    Field namefiled = clazz.getDeclaredField(namevale);
                    namefiled.setAccessible(true);
                    String typestring = namefiled.getType().toString();
                    if (typestring.contains("int")){
                        int i = Integer.parseInt(value);
                        namefiled.set(obj,i);
                    }else{
                        namefiled.set(obj,value);
                    }
                }
                hm.put(idvalue,obj);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Object GetBean(String s){
        return hm.get(s);
    }
}
